package org.dromara.business.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.dromara.business.domain.UserFlowing;
import org.dromara.business.domain.bo.UserFlowingBo;
import org.dromara.business.domain.vo.UserFlowingVo;
import org.dromara.business.mapper.UserFlowingMapper;
import org.dromara.business.service.UserFlowingService;
import org.dromara.common.core.enums.UserType;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.SysUser;
import org.dromara.system.service.ISysUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 用户积分流水Service业务层处理
 *
 * @author zlj
 * @date 2024-08-16
 */
@RequiredArgsConstructor
@Service
public class UserFlowingServiceImpl extends ServiceImpl<UserFlowingMapper, UserFlowing> implements UserFlowingService {

    private final UserFlowingMapper baseMapper;
    private final ISysUserService userService;

    /**
     * 查询用户积分流水
     */
    @Override
    public UserFlowingVo queryById(Long userFlowingId) {
        return baseMapper.selectVoById(userFlowingId);
    }

    /**
     * 查询用户积分流水列表
     */
    @Override
    public TableDataInfo<UserFlowingVo> queryPageList(UserFlowingBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<UserFlowing> lqw = buildQueryWrapper(bo);
        Page<UserFlowingVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询用户积分流水列表
     */
    @Override
    public List<UserFlowingVo> queryList(UserFlowingBo bo) {
        LambdaQueryWrapper<UserFlowing> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<UserFlowing> buildQueryWrapper(UserFlowingBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<UserFlowing> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getAmount() != null, UserFlowing::getAmount, bo.getAmount());
        lqw.eq(bo.getType() != null, UserFlowing::getType, bo.getType());
        lqw.eq(bo.getSubordinateId() != null, UserFlowing::getSubordinateId, bo.getSubordinateId());
        lqw.eq(bo.getCreateBy() != null, UserFlowing::getCreateBy, bo.getCreateBy());
        lqw.eq(ObjectUtil.equal(LoginHelper.getUserType().getUserType(), UserType.XCX_USER.getUserType()), UserFlowing::getCreateBy, LoginHelper.getUserId());
        lqw.orderByDesc(UserFlowing::getCreateTime);
        return lqw;
    }

    /**
     * 新增用户积分流水
     */
    @Override
    public Boolean insertByBo(@Validated(AddGroup.class) UserFlowingBo bo) {
        UserFlowing add = MapstructUtils.convert(bo, UserFlowing.class);

        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setUserFlowingId(add.getUserFlowingId());
        }
        return flag;
    }

    /**
     * 修改用户积分流水
     */
    @Override
    public Boolean updateByBo(UserFlowingBo bo) {
        UserFlowing update = MapstructUtils.convert(bo, UserFlowing.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(UserFlowing entity) {

    }

    /**
     * 批量删除用户积分流水
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {

        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 增加积分
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addAmount(Long userId, BigDecimal amount, Integer type, Long subordinateId) {
        if (amount.compareTo(BigDecimal.ZERO) == 0) {
            return;
        }
        amount = amount.setScale(2, BigDecimal.ROUND_HALF_UP);
        SysUser user = userService.getById(userId);
        if (user.getAmount().add(amount).compareTo(BigDecimal.ZERO) < 0) {
            throw new ServiceException("余额不足");
        }
        boolean update = userService.lambdaUpdate().setSql("amount = amount +" + amount).eq(SysUser::getUserId, userId).update();
        //增加积分记录
        UserFlowingBo userFlowing = new UserFlowingBo();
        userFlowing.setAmount(amount);
        userFlowing.setType(type);
        userFlowing.setSubordinateId(subordinateId);
        userFlowing.setCreateBy(userId);
        this.insertByBo(userFlowing);
    }
}
